import { getUserInfoAPI, LoginAPI } from '@/api/user'
import router from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  userInfo: {}
}

const mutations = {
  saveToken(state, pload) {
    state.token = pload
  },
  saveUserInfo(state, pload) {
    state.userInfo = pload
  }
}

const actions = {
  async loginActions(context, pload) {
    const res = await LoginAPI(pload)
    context.commit('saveToken', res)
    setToken(res)
    Message({
      message: '登录成功',
      type: 'success'
    })
    router.push('/')
  },

  async getUserInfoActions(context) {
    const res = await getUserInfoAPI()
    context.commit('saveUserInfo', res)
  },
  async logoutActions(context) {
    await context.commit('saveToken', '')
    await context.commit('saveUserInfo', {})
    removeToken()
    router.push('/login')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

